package dk.snaveponyklub.persist.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;

import dk.snaveponyklub.handler.HandlerFactory;
import dk.snaveponyklub.util.Logger;


public class HorseCacheImpl {

    Namespace ns = Namespace.getNamespace("s", "http://www.snaveponyklub.dk");
    Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    XMLLoaderImpl loader = new XMLLoaderImpl();
    XMLValidator validator = new XMLValidator();
    Document horses;
	
	public HorseCacheImpl()
	{
		refreshCache();
	}
	
	private void refreshCache() {
		horses = loader.loadHorsesDocument();
	}	

    public void addHorse(String xml) throws Throwable {
    	try {
    		if (validator.isValid(xml, "Persist.xsd")) {
            	Document document = loader.loadXml(xml);
            	XPath xp = XPath.newInstance("//s:horses/s:horse");
                xp.addNamespace(ns);
                Element horse = (Element)xp.selectSingleNode(document);
                horse.setAttribute("id", getNextId());

            	xp = XPath.newInstance("//s:horses");
            	xp.addNamespace(ns);
    			Element horsesElement = (Element)xp.selectSingleNode(horses);            
                
                horsesElement.addContent((Element)horse.clone());
                loader.writeHorses(horses);
                refreshCache();
    		} else { 
    			throw new Throwable("Not valid horse");
    		}
        } catch (JDOMException e) {
            e.printStackTrace();
		}
    }
		
    public Element getHorse(int id) {
        try {
            XPath xp = XPath.newInstance("//s:horse[@id='" + id + "']");
            xp.addNamespace(ns);
            Element horse = (Element)xp.selectSingleNode(horses);
            return horse;
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public Element getHorses() {
        try {
            XPath xp = XPath.newInstance("//s:horses");
            xp.addNamespace(ns);
            Element horsesElement = (Element)xp.selectSingleNode(horses);
            return horsesElement;
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public String getNextId() {
    	int maxId = 1;
        try {
            XPath xp = XPath.newInstance("//s:horses/s:horse");
            xp.addNamespace(ns);
            @SuppressWarnings("unchecked")
			List<Element> horseElements = xp.selectNodes(horses);

            for (Element element : horseElements) {
                try {
                    int id = Integer.parseInt(element.getAttributeValue("id"));
                    if (id > maxId) {
                    	maxId = id;
                    }
                } catch (NumberFormatException e) {
                    Logger.error("Error get id from horse");
                }
			}
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        return (maxId+1)+"";
    }
    
	public static void main(String[] args) throws IOException, Throwable {
		HorseCacheImpl cache = new HorseCacheImpl();
		HandlerFactory.getInstance().addHorse("<s:persist xmlns:s=\"http://www.snaveponyklub.dk\"><s:horses><s:horse id=\"0\"><s:name>EIk</s:name><s:age>15</s:age></s:horse></s:horses></s:persist>");
//    	cache.addHorse("<s:persist xmlns:s='http://www.snaveponyklub.dk'><s:horses><s:horse id=\"0\"><s:name>Hest</s:name><s:age>10</s:age></s:horse></s:horses></s:persist>");
    	Element horses = cache.getHorses();
        XMLOutputter xo = new XMLOutputter();
        xo.output(horses, System.out);
    }	

}
